<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 * @author ml
 * @date 2017-10-19
 */
class Worktask extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('M_work_task');
        $this->load->model('M_work_task_sub');
    }


    /**
     *获取作业任务或通知
     *2017-01-16
     *@param array $info
     *array(
     * "keycode"=>"gzRN53VWRF9BYUXo",//密钥
     * "pid"=>64,//用户id
     * "type"=>1,//0任务1通知
     * "status"=>1,//0为接受1进行中或已完成
     * );
     */
    public function get_work_task_list(){
        try {
//            $_json = true;

//            $_message = method::validate($info, $_json);
            $_message['userid'] = getParam($this->input->get_post("userid", true), 'int');//用户id
            $_message['type'] = getParam($this->input->get_post("type", true), 'int',0);//0任务1通知
            $_message['status'] = getParam($this->input->get_post("status", true), 'int',0);//0为接受进行中1已完成
            $result = array('code'=>0,'data'=>array(),'info'=>'成功');
//            $_message['userid'] = 10002;
//            $_message['type'] = 0;
//            $_message['status']=0;
            if (is_string($_message)){
                return $_message;
            }
            if(empty($_message['userid']))
            {
                $result['code']=1;
                $result['info']='参数不全';
                exit(json_encode($result));
            }
            $where = '';
            if($_message['status']==0){
                $where .=" AND s.work_status < 2";
            }else{
                $where .=" AND s.work_status = 2";
            }
            $sql ="SELECT f.train_number,jp.job_process_name,p.platform_name,t.up_time,t.task_id,s.pub_time,s.work_status,
						f.actualBJtime FROM t_train_task t 
						LEFT JOIN t_train_task_sub s ON t.task_id = s.task_id
						LEFT JOIN t_train_flow f ON f.train_flow_id=t.flow_id
						LEFT JOIN t_platform p ON f.platform_id=p.platform_id
						LEFT JOIN t_job_process_detail d ON d.job_process_detail_id=t.pid
						LEFT JOIN t_job_process jp ON jp.job_process_id=d.job_process_id
						WHERE t.task_type ={$_message['type']} AND s.accepitid ={$_message['userid']} {$where} order by s.pub_time desc";
            $re = $this->M_work_task->querylist($sql);
            if(!empty($re)){
                foreach ($re as $k=>$v)
                {
                    $re[$k]['up_time'] = !empty($v['up_time'])?date('Y-m-d H:i:s',$v['up_time']):'';
                    $re[$k]['start_time'] = !empty($v['actualBJtime'])?date('Y-m-d H:i:s',$v['actualBJtime']):'';
                }
                $result['data']=$re;
                exit(json_encode($result));
            }
            else
            {
                $result['code']=0;
                $result['info']='暂无数据';
                exit(json_encode($result));
            }

        } catch (Exception $e) {
            $result['code']=2;
            $result['info']=$e;
            exit(json_encode($result));
        }
    }
    /**
     *接受作业任务
     *2017-01-16
     *@param array $info
     *array(
     * "keycode"=>"gzRN53VWRF9BYUXo",//密钥
     * "pid"=>64,//用户id
     * "taskid"=>1,//任务id
     * );
     */
    public function accept_work_task(){
        try {
//            $_json = true;
            //判断该任务是否与站台关联，有关联则需要到相应的网格接受任务
            $_message['pid'] = getParam($this->input->get_post("userid", true), 'int');//用户id
            $_message['taskid'] = getParam($this->input->get_post("taskid", true), 'int');//任务id
            $_message['map_id'] = getParam($this->input->get_post("mapid", true), 'int');//网格ID
            $_message['x'] = getParam($this->input->get_post("x", true), 'string' ,'');//维度
            $_message['y'] = getParam($this->input->get_post("y", true), 'string' ,'');//经度
            $_message['grid_floor'] = getParam($this->input->get_post("floor", true), 'int');//楼层
            $result['data'] = '';
//            $_message['pid'] = 81;
//            $_message['taskid'] = 387035;
//            $_message['map_id'] = 2295815;//小网格ID
//            $_message['x'] = 1;
//            $_message['grid_floor'] = 2320340;
//            $_message['y'] = 1;
            foreach ($_message as $val)
            {
                if(empty($val))
                {
                    $result['code']=1;
                    $result['info']='参数不全';
                    exit(json_encode($result));
                }
            }
//            $_message = method::validate($info, $_json);
//            if (is_string($_message)){
//                return $_message;
//            }
            $time= time();
//            $handModel = Model::singleton('bjnz_train_task');

            $ssql="select task_id,task_style,post_type_id,post_id from t_train_task where task_id={$_message['taskid']} and (task_status=0 or task_status=2 or task_status=5 or task_status=6)";
//            $s = $handModel->db->fetch($ssql);
            $s = $this->M_work_task->querylist($ssql);
            if(!empty($s)){
                $result['code']=1;
                $result['info']='接收失败,请重新刷新页面!';
                exit(json_encode($result));
//                return method::output(0,'接收失败,请重新刷新页面!','501',$_json);
            }
            if(!empty($_message['map_id'] )){
                $this->load->model('M_t_grid_w');
                $mapid = $this->M_t_grid_w->getOne('grid_id',array('small_grid_id'=>$_message['map_id']));
            }
            else{
                $mapid=0;
            }
            if($mapid==0 ||empty($mapid))
            {
                $result['code']=1;
                $result['info']='网格ID异常!';
                exit(json_encode($result));
            }
            $sssql = "select p.grid_id,t.task_style from t_train_task t 
                      LEFT JOIN t_train_flow f ON t.flow_id=train_flow_id 
                      LEFT JOIN t_platform p ON f.platform_id=p.platform_id
                      where t.task_id={$_message['taskid']}";
            $ss = $this->db->query($sssql)->row_array();
            if($ss['task_style'] == 1)//与站台关联
            {
                if($ss['grid_id'] != $mapid)
                {
                    $result['code']=1;
                    $result['info']='请到相应站台接受任务!';
//                    exit(json_encode($result));
                }
            }
            $sql="UPDATE t_train_task_sub SET work_status =1,start_time={$time},grid_id={$mapid},x={$_message['x']},y={$_message['y']},grid_floor={$_message['grid_floor']} WHERE task_id ={$_message['taskid']} AND accepitid ={$_message['pid']}";
//            $re =$this->M_t_grid_w->exec($sql);
            $re =$this->db->query($sql);
            $sql2 ="delete from t_train_task_sub  where task_id ={$_message['taskid']} AND work_status =0";
//            $rs =$this->M_t_grid_w->exec($sql2);
            $rs =$this->db->query($sql2);
            $opsql="UPDATE t_train_task set task_status =5 where task_id={$_message['taskid']}";
//            $this->M_t_grid_w->exec($opsql);
            $this->db->query($opsql);
            if(!empty($re)){
                //获取任务的列车流水id及任务代号
                $sql1 ="SELECT flow_id,code_id,task_type FROM t_train_task WHERE task_id = {$_message['taskid']}";
//                $res = $handModel->db->fetch($sql1);
                //发送PC业务广播
//                $result = method::sendBroadcast($_message['taskid']);

                /**************************** 接受任务时记录坐标点***************************************/
                //接受任务成功 插入一条数据
//                $sql = "select t_bjnz_map_id from t_bjnz_map_w where id = ".$_message['map_id'];
//                $map_id = $handModel->db->fetch($sql);
//                if(!empty($map_id['t_bjnz_map_id'])){
//                    $ti_me = time();
//                    $sql = "INSERT INTO t_bjnz_map_task(PID,x,addtime,y,tid,map,mid) VALUES ('{$_message['PID']}','{$_message['x']}','{$ti_me}','{$_message['y']}','{$_message['taskid']}',2,'{$map_id['t_bjnz_map_id']}')";//增加floor字段到mid,昨夜任务map为2.
//                    $handModel->db->query($sql);
//                }
                /****************************************************************/
                $result['code']=0;
                $result['info']='接受成功!';
                exit(json_encode($result));
//                return method::output(1,'接受成功','500',$_json);
            }
            $result['code']=0;
            $result['info']='接收失败!';
            exit(json_encode($result));
//            return method::output(0,'接收失败','501',$_json);

        } catch (Exception $e) {
            $result['code']=2;
            $result['info']=$e;
            exit(json_encode($result));
//            return method::output(0,$e->getMessage(),'502',$_json);
        }

    }

    /**
     *完成作业任务或确认任务通知
     *2017-01-16
     *@param array $info
     *array(
     * "keycode"=>"gzRN53VWRF9BYUXo",//密钥
     * "pid"=>64,//用户id
     * "taskid"=>1,//任务id
     * );
     */
    public function save_work_task(){
        try {
//            $_json = true;

//            $_message = method::validate($info, $_json);
//            if (is_string($_message)){
//                return $_message;
//            }
            $_message['pid'] = getParam($this->input->get_post("userid", true), 'int');//用户id
            $_message['taskid'] = getParam($this->input->get_post("taskid", true), 'int');//任务id
            $_message['map_id'] = getParam($this->input->get_post("mapid", true), 'int');//网格ID
            $_message['x'] = getParam($this->input->get_post("x", true), 'string' ,'');//维度
            $_message['y'] = getParam($this->input->get_post("y", true), 'string' ,'');//经度
            $_message['grid_floor'] = getParam($this->input->get_post("floor", true), 'int');//楼层
            $result['data'] = '';
//            $_message['pid'] = 86;
//            $_message['taskid'] = 387094;
//            $_message['map_id'] = 2295736;//小网格ID
//            $_message['x'] = 1;
//            $_message['y'] = 1;
            $time= time();
//            $handModel = Model::singleton('bjnz_train_task');
            $sqln ='';
            if(!empty($_message['text'])&&isset($_message['text'])){
                $sqln .= ", `Contents`='{$_message['text']}'";
            }
            if(!empty($_message['sound'])&&isset($_message['sound'])){
                $sqln .= ", `sound` = '{$_message['sound']}'";
            }

            // file_put_contents('text.txt',$sql,FILE_APPEND);
            $info = $this->M_work_task_sub->getRow('task_sub_id',array('task_id'=>$_message['taskid'],'accepitid'=>$_message['pid']));
            if(empty($info)){
                $result['code']=1;
                $result['info']='作业不存在或已取消!';
                exit(json_encode($result));
            }

            //接受任务成功 修改接受时的网格id
            if(!empty($_message['map_id'] )){
                $this->load->model('M_t_grid_w');
                $mapid = $this->M_t_grid_w->getOne('grid_id',array('small_grid_id'=>$_message['map_id']));
            }
            else{
                $mapid=0;
            }
            if($mapid==0 ||empty($mapid))
            {
                $result['code']=1;
                $result['info']='网格ID异常!';
                exit(json_encode($result));
            }
            $sssql = "select p.grid_id,t.task_style from t_train_task t 
                      LEFT JOIN t_train_flow f ON t.flow_id=train_flow_id 
                      LEFT JOIN t_platform p ON f.platform_id=p.platform_id
                      where t.task_id={$_message['taskid']}";
            $ss = $this->db->query($sssql)->row_array();
            if($ss['task_style'] == 1)//与站台关联
            {
                if($ss['grid_id'] != $mapid)
                {
                    $result['code']=1;
                    $result['info']='请到相应站台接受任务!';
//                    exit(json_encode($result));
                }
            }
            // $sql="UPDATE t_train_task_sub SET wangge_id =$mapid[t_bjnz_map_id] WHERE taskid ={$_message['taskid']} AND accepitid ={$_message['pid']}";
            // $re1 =$handModel->db->query($sql);
            /****************************************************************/
            $sql="UPDATE t_train_task_sub SET work_status =2,stop_time={$time},done_time={$time},grid_id={$mapid},x={$_message['x']},y={$_message['y']},grid_floor={$_message['grid_floor']} {$sqln} WHERE task_id ={$_message['taskid']} AND accepitid ={$_message['pid']}";

            $re =$this->db->query($sql);

//            $sql2 ="delete from t_train_task_sub  where task_id ={$_message['taskid']} AND work_status =0";
//            $rs =$this->db->query($sql2);

            if(!empty($_message['file'])&&isset($_message['file'])){
                foreach($_message['file'] as $key=>$val){
                    $sql = "INSERT INTO `t_train_task_file` (`AccountId`, `TaskSubId`,`FileName`,`PathName`, `FilePath`, `Cid`, `CreateTime`) VALUES (131785, '{$info['id']}','{$val['old_name']}', '{$val['new_name']}','{$val['file']}', '{$_message['pid']}', '{$time}')";
                    $result = $this->db->query($sql);
                }
            }
            //获取任务的列车流水id及任务代号
            $res = $this->M_work_task->getOne('flow_id,code_id,task_type',array('task_id'=>$_message['taskid']));
//            $sql1 ="SELECT flowid,codeid,tasktype FROM t_train_task WHERE id = {$_message['taskid']}";
//            $res = $handModel->db->fetch($sql1);
//            $return = self::gettaskchild($res['flowid'],$res['codeid']);
            $opsql="UPDATE t_train_task set task_status =6 where task_id={$_message['taskid']}";
            $this->db->query($opsql);

            if(!empty($re)){
                //推送PC业务广播
                /*if($res['tasktype'] == 1){
                    $result = method::sendBroadcast($_message['taskid']);
                }*/

                /**************************** 完成任务时记录坐标点***************************************/
                $result['code']=0;
                $result['info']='成功!';
                exit(json_encode($result));
            }
            $result['code']=1;
            $result['info']='失败!';
            exit(json_encode($result));

        } catch (Exception $e) {
            $result['code']=2;
            $result['info']=$e;
            exit(json_encode($result));
        }

    }
    //获取作业任务详情
    public function get_work_task_detail()
    {
        //缺少流程监控，有监控要显示所有任务
        $task_id = getParam($this->input->get_post("taskid", true), 'int');//任务id
        $user_id = getParam($this->input->get_post("userid", true), 'int');//用户id
//        $user_id=67;
//        $task_id=387013;
        if(empty($task_id) || empty($user_id))
        {
            exit(json_encode(array('code'=>1,'data'=>array(),'info'=>'参数不全！')));
        }
        $sql = "select  s.work_status,f.train_number,jp.job_process_name,f.train_flow_id,j.is_control,s.receive_user_id,j.job_content,j.job_benchmark,po.post_name,f.platform_id,p.platform_name,f.actualBJtime,s.done_time from t_train_task t 
                LEFT JOIN t_train_flow f ON t.flow_id=f.train_flow_id
                LEFT JOIN t_train_task_sub s ON t.task_id=s.task_id
                LEFT JOIN t_platform p ON f.platform_id=p.platform_id
                LEFT JOIN t_post po ON t.post_id=po.post_id
                LEFT JOIN t_job_process_detail d ON d.job_process_detail_id=t.pid
                LEFT JOIN t_job_process jp ON jp.job_process_id=d.job_process_id
                LEFT JOIN t_job j ON d.job_id=j.job_id
                where t.task_id=$task_id AND s.receive_user_id=$user_id";
        $data = $this->db->query($sql)->row_array();
        $data['receive_time'] = $data['actualBJtime']!=''?date('Y-m-d H:i:s',$data['actualBJtime']):'';
        $data['done_time'] = $data['done_time']!=''?date('Y-m-d H:i:s',$data['done_time']):'';
        $list = array();
        $res = array();
        if($data['is_control']==1)//可以查看该车次所有任务
        {
            $sql = "SELECT p.platform_name p_name,t.flow_id,flow.train_number,flow.train_begin_time,flow.train_end_time,u.user_name,t.task_id, t.task_info_id, t.task_name, t.task_type, t.task_status, t.post_id, w.post_id AS wid, w.post_type_id AS wtype, w.post_name AS wname, t.pid AS fid, t.code_pid, t.code_id, IFNULL(t.up_time, 0) uptime, ts.accepitid, ts.receive_user_id, ts.pub_time, ts.work_status 
                    FROM t_train_task t LEFT JOIN t_train_flow flow ON t.flow_id=flow.train_flow_id 
                    LEFT JOIN t_platform p ON p.platform_id=flow.platform_id
                    LEFT JOIN t_train train ON flow.train_id=train.train_id LEFT JOIN t_post w ON t.post_id = w.post_id 
                    LEFT JOIN t_train_task_sub ts ON t.task_id = ts.task_id LEFT JOIN t_user u ON u.user_id=ts.receive_user_id 
                    WHERE t.flow_id = {$data['train_flow_id']} ORDER BY t.task_id";
//                AND ts.work_status > 0 WHERE t.flow_id = {$data['train_flow_id']} ORDER BY t.task_id";
            $list = $this->db->query($sql)->result_array();
            foreach ($list as $k=>$v)
            {
                $res[$k]['name'] = $v['train_number'].$v['wname'].$v['task_name'];
                $res[$k]['p_name'] = $v['p_name'];
                $res[$k]['user_name'] = $v['work_status'] == 0 ? '':$v['user_name'];
                $res[$k]['wname'] = $v['work_status'] == 0 ? '':$v['wname'];
                switch ($v['work_status'])
                {
                    case "0":
                        $res[$k]['status'] = "未接收";
                        break;
                    case "1":
                        $res[$k]['status'] = "进行中";
                        break;
                    case "2":
                        $res[$k]['status'] = "已完成";
                        break;
                    default:
                        $res[$k]['status'] = "未接收";
                        break;
                }
                /*switch($v['task_status'])
                {
                    case "0":
                        $list[$k]['status'] = "未确认";
                        break;
                    case "1":
                        $list[$k]['status'] = "正常";
                        break;
                    case "2":
                        $list[$k]['status'] = "已取消";
                        break;
                    case "3":
                        $list[$k]['status'] = "已触发";
                        break;
                    case "4":
                        $list[$k]['status'] = "已发送";
                        break;
                    case "5":
                        $list[$k]['status'] = "已接受";
                        break;
                    case "6":
                        $list[$k]['status'] = "已完成";
                        break;
                    default:
                        $list[$k]['status'] = "无法确认状态";
                        break;
                }*/
            }
        }
        //删除无用数据
        unset($data['is_control']);
        unset($data['done_time']);
        unset($data['actualBJtime']);
        exit(json_encode(array('code'=>0,'data'=>array('result'=>$res,'list'=>$data),'info'=>'成功')));

    }
    //返回小网格名称小网格ID
    public function arear(){
        $floor = $this->input->get_post('floor',true);//楼层
        $map_id = $this->input->get_post("map_id", true);//所属网格标示
        $x = $this->input->get_post('x',true);//x
        $y= $this->input->get_post('y',true);//y
        if(empty($map_id)){
            exit(json_encode(array('code'=>1,'data'=>array(),'info'=>'参数不全！')));
        }
        if($map_id){
            $sql = "SELECT m.area FROM t_grid_w w LEFT JOIN t_grid m ON w.t_grid_id=m.id WHERE w.id=".$map_id;
            $data = $this->db->query($sql)->row_array();
        }
        $this->printJson_data($data);
        // var_dump($data);
    }
    //登录岗位生成作业任务
    public function create_post_task($userid,$workid)
    {
//        $userid = getParam($this->input->get_post("userid", true), 'int');//用户id
//        $workid = getParam($this->input->get_post("workid", true), 'int');//岗位id
//        $userid = "63";
//        $workid = "8"; //64,81
        $time = time();
        $string = "";
        $sql = "select t.task_id from t_train_task t LEFT JOIN t_train_flow f on t.flow_id=f.train_flow_id
                where f.train_status=1 AND f.train_flow_statu<>1 AND f.is_open=1 AND t.post_type_id=2 AND t.task_status=4 AND FIND_IN_SET('$workid',t.post_id) GROUP by t.task_id";
        $res = $this->db->query($sql)->row_array();
        if(empty($res))
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'无任务')));
        }
        else
        {
            $sql ="select * from t_train_task_sub where receive_user_id={$userid} AND task_id={$res['task_id']}";
            if($this->db->query($sql)->num_rows()>0)
            {
                exit(json_encode(array('code'=>1,'data'=>'','info'=>'已存在任务')));
            }
        }
        $string .= "({$res['task_id']},{$userid},'{$userid}',{$time},0)";
        if(empty($string))
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'无任务')));
        }
        $usql ="insert into t_train_task_sub(task_id,accepitid,receive_user_id,receive_time,work_status) VALUES {$string}";
        $res1 = $this->db->query($usql);
        if($res1)
        {
            exit(json_encode(array('code'=>0,'data'=>'','info'=>'成功')));
        }
        else
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'失败')));
        }

    }
    //记录位置信息
    public function addMap(){
        $PID = $this->input->get_post("PID", true);//用户id
        $floor = $this->input->get_post("floor", true);//楼层
        $mapid =  $this->input->get_post("mapid", true);//地图标识
        $map_id = $this->input->get_post("map_id", true);//所属网格标示
        $x = $this->input->get_post('x',true);//x
        $y= $this->input->get_post('y',true);//y
        $age = getParam($this->input->get_post("age", true), 'string' ,'');//age    string
        //$age = $this->input->get_post('age',true);//age	string	定位时间距离当前时间的差值
        $mac = $this->input->get_post('mac',true);//age	string	定位时间距离当前时间的差值
        $wname = $this->input->get_post("wname", true);//楼层
        if(empty($PID) || empty($floor) || empty($mapid) || empty($x) || empty($y) || empty($mac)){
            exit(json_encode(array('code'=>2001,'data'=>array(),'info'=>'参数不全！')));
        }
        if($map_id){
            $this->load->model('M_t_grid_w');
            $map_id = $this->M_t_grid_w->getOne('t_grid_id',array('id'=>$map_id));
        }
        $data = array(
            'PID'=>$PID,
            'floor'=>$floor,
            'mapid'=>$mapid,
            'map_id'=>$map_id,
            'x'=>$x,
            'y'=>$y,
            'addtime'=>time(),
            'age'=>$age,
            'mac'=>$mac,
            'wname'=>$wname,
        );
        $this->load->model('M_t_bjnz_user_map_copy');
        $this->M_t_bjnz_user_map_copy->saveData($data);
        $this->printJson_data($data);

    }

    /**
     *推送作业提醒
     *$name 发送人
     *$content 内容
     *$username 接受人
     *$title 标题
     *$tourl 地址
     */
    private static function sendmess($name,$content,$username,$title,$tourl,$type='task'){
        $keycode = Cfg::get('wisetong.keycode');
        $accountid = '131785';
        $receiveuser = array();

        $url = Cfg::get('wisetong._domain_addr') . "/index.php/admin/user/login?wiseuc=";
        $md5_key = 'wiseuc20140831';
        $jump = urlencode($tourl);

        $urlstr = '';
        $passwd = md5($username.$keycode.substr($md5_key, -9));
        $urlstr = 'username='.$username.'&k='.$md5_key.'&v='.$passwd.'&action=&jump='.$jump.'&client=3.0&version=3.9';

        $newurl = $url . base64_encode($urlstr);

        $xml = '<vibration>0</vibration><messagetype>'.$type.'</messagetype><appid>126</appid><color>#FF0000</color>';

        $arr = array(
            'sendname' =>$name,
            'receive' => $username,
            'title' => $title,
            'content' => $content,
            'url' => $newurl,
            'style' => '1',
            'showtype' => 'webmsg',
            'opttype' => 'day',
            'keycode' => $keycode,
            'xml' => $xml
        );
        $receiveuser[] = $arr;

        if(empty($receiveuser)){
            return true;
        }

        $args = json_encode($receiveuser);

        $host = Cfg::get('wisetong._soap_addr');;
        $soap = new soapClient($host);
        $result = $soap->sendmsgs($args);
        return $result;
    }
}